<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>案例_分类导航</title>
  <link rel="stylesheet" href="./css/index.css">
</head>

<body>
  <!-- 大容器 -->
  <div class="container">
    <div class="sub-list">
      <div class="item">
        <h3>分类名字</h3>
        <ul>
          <li>
            <a href="javascript:;">
              <img src="http://zhoushugang.gitee.io/erabbit-client-pc-static/uploads/img/category%20(9).png" />
              <p>巧克力</p>
            </a>
          </li>
          <li>
            <a href="javascript:;">
              <img src="http://zhoushugang.gitee.io/erabbit-client-pc-static/uploads/img/category%20(9).png" />
              <p>巧克力</p>
            </a>
          </li>
          <li>
            <a href="javascript:;">
              <img src="http://zhoushugang.gitee.io/erabbit-client-pc-static/uploads/img/category%20(9).png" />
              <p>巧克力</p>
            </a>
          </li>
        </ul>
      </div>
    </div>
  </div>
  <script src="https://unpkg.com/axios@0.21.1/dist/axios.min.js"></script>

  <script>
    /**
     * 目标：把所有商品分类“同时”渲染到页面上
     *  1. 获取所有一级分类数据
     *  2. 遍历id，创建获取二级分类请求
     *  3. 合并所有二级分类Promise对象
     *  4. 等待同时成功后，渲染页面
    */

    axios({
      url: 'http://hmajax.itheima.net/api/category/top',
    }).then(async res => {
      // 当代码解析到箭头函数 相当于一个代码体 当前没有返回值  没有东西出来
      const list = res.data.data.map(({ id }) => axios({ url: 'http://hmajax.itheima.net/api/category/sub', params: { id } }))
      console.log(list);
      try {
        const rers2 = await Promise.all(list)   //防止失败try catch
        // 接收到res2的结果
        const subList = document.querySelector('.sub-list')
        console.log(rers2);
        subList.innerHTML = rers2.map(({ data: { data: { name, children } } }) => {
          // 先处理二级分类  将二级分类放到一级分类中
          const lisStr = children.map((item) => {
            return `
              <li>
               <a href="javascript:;">
              <img src="${item.picture}" />
              <p>${item.name}</p>
                </a>
             </li>
            `
          }).join('')
          return `
           <div class="item">
               <h3>${name}</h3>
                   <ul>
                   ${lisStr}
                  </ul>
            </div>
          `
        }).join('')

      } catch (error) {
        console.log(error);
      }

    })



  </script>
</body>

</html>